package com.boot.web.util;

import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;

/**
 * @author 霜寒 <1621856595@qq.com>
 * @description HTTP 请求工具
 * @date 2020/2/24 14:06
 **/

public class HttpRequestUtil {

    private static RestTemplate restTemplate;

    static {
        restTemplate = new RestTemplate();
        restTemplate.setErrorHandler(new BootResponseErrorHandler());
        restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
    }

    public static RestTemplate getRestTemplate() {
        return restTemplate;
    }

    public static <S, T> ResponseEntity<T> request(Request<S> request, Class<T> clazz) {
        if (request.getParams() == null || request.getParams().size() == 0) {
            return restTemplate.exchange(request.getUrl(),
                    request.getMethod(),
                    request.getEntity(),
                    clazz);
        } else {
            return restTemplate.exchange(request.getUrl(),
                    request.getMethod(),
                    request.getEntity(),
                    clazz,
                    request.getParams());
        }
    }

    public static <S, T> ResponseEntity<T> request(Request<S> request, ParameterizedTypeReference<T> typeReference) {
        if (request.getParams() == null || request.getParams().size() == 0) {
            return restTemplate.exchange(request.getUrl(),
                    request.getMethod(),
                    request.getEntity(),
                    typeReference);
        } else {
            return restTemplate.exchange(request.getUrl(),
                    request.getMethod(),
                    request.getEntity(),
                    typeReference,
                    request.getParams());
        }

    }

    private static class BootResponseErrorHandler extends DefaultResponseErrorHandler {
        @Override
        public boolean hasError(ClientHttpResponse response) throws IOException {
            return response.getRawStatusCode() >= 500;
        }
    }

}
